// pages/application-records/application-records.js
const app = getApp()

Page({
  data: {
    // 筛选状态
    filterStatus: [
      { label: '全部', value: '' },
      { label: '待处理', value: 'pending' },
      { label: '已通过', value: 'accepted' },
      { label: '已拒绝', value: 'rejected' },
      { label: '已取消', value: 'cancelled' }
    ],
    currentStatus: '', // 当前选择的状态

    // 统计数据
    stats: {
      totalCount: 0,
      pendingCount: 0,
      approvedCount: 0,
      rejectedCount: 0
    },

    // 申请记录列表
    applicationRecords: [],
    loading: false,
    hasMore: true,
    page: 1,
    pageSize: 10
  },

  onLoad() {
    this.loadApplicationRecords()
  },

  onShow() {
    // 每次显示时刷新数据
    this.setData({
      page: 1,
      applicationRecords: [],
      hasMore: true
    })
    this.loadApplicationRecords()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      applicationRecords: [],
      hasMore: true
    })
    this.loadApplicationRecords()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadApplicationRecords()
    }
  },

  // 加载申请记录
  async loadApplicationRecords() {
    if (this.data.loading) return

    this.setData({ loading: true })

    try {
      if (!app.globalData.token) {
        wx.reLaunch({
          url: '/pages/login/login'
        })
        return
      }

      const result = await app.utils.request({
        url: '/application/records',
        method: 'GET',
        data: {
          status: this.data.currentStatus
        }
      })

      wx.stopPullDownRefresh()

      if (result.code === 200) {
        const data = result.data
        
        // 更新统计数据（适配后端返回结构）
        const stats = data.stats || {}
        this.setData({
          stats: {
            totalCount: stats.total || 0,
            pendingCount: stats.pending || 0,
            approvedCount: stats.accepted || 0,
            rejectedCount: stats.rejected || 0
          }
        })

        // 处理申请记录数据
        const records = (data.records || []).map(item => ({
          ...item,
          id: item.id,
          targetId: item.laborId || item.id, // 关联的劳务ID
          type: item.applicationType || 'labor',
          title: item.title,
          description: item.description,
          salary: item.reward,
          location: item.location,
          status: item.status,
          applicationNote: item.applicationNote,
          replyNote: item.reviewNote || item.completeNote,
          createTime: item.applicationTime,
          statusText: this.getStatusText(item.status),
          statusClass: `status-${item.status}`,
          typeText: this.getTypeText(item.applicationType || 'labor'),
          createTimeText: this.formatTime(item.applicationTime)
        }))

        this.setData({
          applicationRecords: this.data.page === 1 ? records : [...this.data.applicationRecords, ...records],
          hasMore: records.length === this.data.pageSize,
          page: this.data.page + 1,
          loading: false
        })
      } else {
        throw new Error(result.message || '获取申请记录失败')
      }
    } catch (error) {
      wx.stopPullDownRefresh()
      console.error('获取申请记录失败:', error)
      this.setData({ loading: false })
      
      if (error.message && error.message.includes('Token')) {
        wx.reLaunch({
          url: '/pages/login/login'
        })
      } else {
        app.utils.showError(error.message || '获取申请记录失败')
      }
    }
  },

  // 切换筛选状态
  onStatusFilter(e) {
    const status = e.currentTarget.dataset.status
    this.setData({
      currentStatus: status,
      page: 1,
      applicationRecords: [],
      hasMore: true
    })
    this.loadApplicationRecords()
  },

  // 查看申请详情
  viewApplicationDetail(e) {
    const item = e.currentTarget.dataset.item
    const itemStr = encodeURIComponent(JSON.stringify(item))
    
    if (item.type === 'labor') {
      // 跳转到劳务详情页
      wx.navigateTo({
        url: `/pages/labor/detail/detail?id=${item.targetId}&from=application&applicationData=${itemStr}`
      })
    }
  },

  // 取消申请
  async cancelApplication(e) {
    const item = e.currentTarget.dataset.item
    
    wx.showModal({
      title: '确认取消',
      content: `确定要取消申请「${item.title}」吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' })
            
            const result = await app.utils.request({
              url: '/application/cancel',
              method: 'POST',
              data: {
                applicationId: item.id,
                applicationType: item.type
              }
            })
            
            wx.hideLoading()
            
            if (result.code === 200) {
              wx.showToast({
                title: '已取消申请',
                icon: 'success'
              })
              
              // 刷新列表
              this.setData({
                page: 1,
                applicationRecords: [],
                hasMore: true
              })
              this.loadApplicationRecords()
            } else {
              throw new Error(result.message || '取消申请失败')
            }
          } catch (error) {
            wx.hideLoading()
            console.error('取消申请失败:', error)
            app.utils.showError(error.message || '取消申请失败')
          }
        }
      }
    })
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待处理',
      'accepted': '已通过',
      'approved': '已通过',
      'rejected': '已拒绝',
      'cancelled': '已取消',
      'completed': '已完成'
    }
    return statusMap[status] || '未知状态'
  },

  // 获取类型文本
  getTypeText(type) {
    const typeMap = {
      'labor': '劳务',
      'substitute': '代课',
      'express': '快递',
      'errand': '跑腿'
    }
    return typeMap[type] || '其他'
  },

  // 格式化时间
  formatTime(dateStr) {
    if (!dateStr) return ''
    
    const date = new Date(dateStr)
    const now = new Date()
    const diff = now - date
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚'
    }
    
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前'
    }
    
    // 小于24小时
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前'
    }
    
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前'
    }
    
    // 超过7天显示具体日期
    return date.getFullYear() === now.getFullYear() 
      ? `${date.getMonth() + 1}-${date.getDate()}`
      : `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  },

  // 去浏览任务
  goToBrowse() {
    wx.switchTab({
      url: '/pages/labor/list/list'
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  }
})